package edu.cmu.cs211.exprtree.ast;

import java.math.BigDecimal;
import java.util.Map;

/**
 * An expression representing an unknown, for example `x'.
 *
 * Edits you make to this class will be ignored by Frontdesk.
 */
public final class VariableExpression implements Expression {
	private final String name;

	/**
	 * Creates a new variable expression.
	 * 
	 * @param name
	 *            the name for the new expression
	 * @throws NullPointerException if name is null
	 */
	public VariableExpression (String name) {
		if (name == null)
			throw new NullPointerException ();
		this.name = name;
	}

	/** An accessor for the name of the expression */
	public String getName ()
	{
		return name;
	}
	
	public BigDecimal evaluate (Map<String,BigDecimal> m) {
		if(!m.containsKey(name))
			throw new IllegalArgumentException("Variable '" + name + "'and  remains unassigned");
		return m.get(name);
	}

	/** A nop (an unknown is...unknown) */
	public Expression cfold ()
	{
		return this;
	}

	/** @return the string from getName () */
	@Override
	public String toString ()
	{
		return getName ();
	}

	@Override
	public boolean equals (Object obj)
	{
		if (!(obj instanceof VariableExpression))
			return false;
		return ((VariableExpression) obj).name.equals (name);
	}

	@Override
	public int hashCode ()
	{
		return name.hashCode ();
	}
}
